﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.InvoiceAndReceiptManage;

using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;
using ProduceBasicData.Domain.InvoiceAndReceiptManage;

namespace ProduceBasicData.Api.Application.Handler.InvoiceAndReceiptManage
{
    /// <summary>
    /// 到票录入处理类
    /// </summary>
    public class CreateReceiptHandler : IRequestHandler<CreateReceiptCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Receipt> _receiptRepository;
        private readonly IMapper _mapper;
        private readonly ICodeRuleService codeRuleService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="receiptRepository"></param>
        /// <param name="mapper"></param>
        public CreateReceiptHandler(IBaseRespository<Receipt> receiptRepository, IMapper mapper,
            ICodeRuleService codeRuleService)
        {
            _receiptRepository = receiptRepository;
            _mapper = mapper;
            this.codeRuleService = codeRuleService;
        }
        /// <summary>
        /// 处理到票录入请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateReceiptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //将命令转换为领域模型
                var receipt = _mapper.Map<Receipt>(request);
                //编码
                if (string.IsNullOrEmpty(receipt.SytemNo))
                {
                    var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.InvoiceToTicketManage.Receipt");
                    if (!string.IsNullOrEmpty(code))
                    {
                        receipt.SytemNo = code;
                    }
                    else
                    {
                        receipt.SytemNo = $"KP{DateTime.Now:yyyyMMddHHmmss}";
                    }
                }
                //判断到票是否存在
                var receiptExist = await _receiptRepository.GetAll().AnyAsync(x => x.SytemNo == receipt.SytemNo);
                if (receiptExist != false)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "到票已存在"
                    };
                }


                //保存到票
                var result = await _receiptRepository.AddAsync(receipt);
                if (result > 0)
                {
                    return new ApiResult<int>
                    {
                        Data = result,
                        Code = ApiEnum.Success,
                        Msg = "到票录入成功"
                    };
                }
                else
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "到票录入失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = ex.Message
                };
            }
        }
    }
}
